import routes from '@/routes';
import { IMenuItem, IRouteItem } from '@/routes/RouteType';
import { getMenuInfoByPath, getValidMenus } from '@/routes/RouteUtil';
import { homeRoutes, mainRoutes } from '@/routes/modules/menus';
import { MenuProps } from 'antd';
import { useCallback, useEffect, useState } from 'react';
import { NavigateOptions, useLocation, useNavigate } from 'react-router-dom';
import { MenuLayout } from './AppStyle';

interface Props extends MenuProps {
  menuData?: IRouteItem[];
  isHome?: boolean;
  ignoreHide?: boolean;
}

export const AppMenu: React.FC<Props> = (props) => {
  const { menuData, isHome, ignoreHide, mode = 'horizontal', ...rest } = props;
  const navigate = useNavigate();
  const { pathname } = useLocation();

  const [menuItems, setMenuItems] = useState<IMenuItem[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [openKeys, setOpenKeys] = useState<string[]>([]);

  const navigateTo = useCallback((path: string) => {
    let redirectPath = path;
    let redirectParams: NavigateOptions = {};
    const { currentMenu } = getMenuInfoByPath(routes, redirectPath);

    if (currentMenu) {
      if (currentMenu?.redirect) {
        if (typeof currentMenu?.redirect === 'string') {
          redirectPath = currentMenu?.redirect;
        } else {
          redirectPath = currentMenu?.redirect?.to;
          redirectParams = currentMenu.redirect?.options || {};
        }
      }
      navigate(redirectPath, redirectParams);
    }
  }, []);

  const menuItemClick: MenuProps['onClick'] = (e) => {
    navigateTo(e.key);
  };

  useEffect(() => {
    const navData = menuData || (isHome ? homeRoutes : mainRoutes);
    let validMenus = getValidMenus(navData, [], ignoreHide).map((item) => {
      const { key, label, icon, disabled, children, type, target } = item;

      let labelElem = label;
      if (target) {
        labelElem = (
          <a href={`${key}`} target={target} rel="noopener noreferrer">
            {labelElem}
          </a>
        );
      }

      return {
        key,
        label: labelElem,
        type,
            icon,
            disabled,
        children,
      };
    });

    setMenuItems(validMenus);
  }, [menuData, isHome, ignoreHide]);

  useEffect(() => {
    if (pathname) {
      const { parentKeys } = getMenuInfoByPath(routes, pathname);
      if (parentKeys.length > 0) {
        setSelectedKeys(parentKeys);
        setOpenKeys(parentKeys);
      }
    }
  }, [pathname]);

  return (
    <MenuLayout
      {...rest}
      selectedKeys={selectedKeys}
      // defaultSelectedKeys={selectedKeys}
      // defaultOpenKeys={openKeys}
      openKeys={openKeys}
      mode={mode}
      items={menuItems}
      onClick={menuItemClick}
      // 注意这个属性 `onOpenChange`
      onOpenChange={(oKeys) => {
        setOpenKeys(oKeys);
      }}
    />
  );
};
